import { BaseService } from '@app/db/base/base.service';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SysConfig } from '../entity/SysConfig';

@Injectable()
export class SysConfigRepositoryService extends BaseService<SysConfig>{
    constructor(
        @InjectRepository(SysConfig) protected repository:Repository<SysConfig>
    ) {
        super()
        this.primaryKey = 'id'
    }

    async selectValues(code:string, ...fields:string[]) {

        const configs:{[key:string] : any} = {}

        if(fields.length > 0) {
            const arr:string[] = []
            fields.forEach(field => {
                arr.push(`JSON_EXTRACT(config, CONCAT('$.', '${field}', '.value')) AS \`${field}\``)
            })

            const items = await this.query(`select ${arr.join(',')} from ${this.tableName} where code = '${code}'`)

            items.forEach(item => {

                for(let k in item) {
                    configs[k] = item[k]
                }
            })

        }else {
            const sysConfig = await this.findOne({code : code})
            if(sysConfig != null) {
                for(let k in sysConfig.config) {
                    configs[k] = sysConfig.config[k].value
                }
            }
        }

        return configs
    }

    async selectValue(code:string, field:string) {
        const configs = await this.selectValues(code, field)
        return field in configs ? configs[field] : null
    }


}